/*
@STI LICENSE
(C) 2006-2008 Universit�t Innsbruck.

This file is part of myOntology.

myOntologyis free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

myOntologyis distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with myOntology.  If not, see <http://www.gnu.org/licenses/>.

@STI LICENSE */
package view.HTMLUIcomponents;

import java.util.ArrayList;

import model.Labels;
import model.Vocabulary;

import org.apache.commons.lang.StringEscapeUtils;
import org.jtb.quickr.PhotoResponse;
import org.jtb.quickr.PhotosService;
import org.openrdf.model.URI;

import controller.HelperFunctions;
import controller.elementMapper.Mapper;


public class Images extends AbstractComponent {
	

	public static final String CSSIDFIELD = "divimages";
	public static final String CSSIDCONTENT = "divimagescontent";
	public static final String NAMEFORMELEMENT = "flickrImagesEntry";
	
	public static final String FOCUSIDOFEDITPANEL = NAMEFORMELEMENT + "_input";
	

	public static String getEmptyFieldContainer() {

		String ret = AbstractComponent.getEmptyFieldContainer( CSSIDFIELD );
		
		return ret;
	}
	
	public static String getLinkToShowSecondaryFieldInEditMode( boolean shownavigationInEditField ) {
				
		return getLinkToShowSecondaryFieldInEditMode(CSSIDFIELD, shownavigationInEditField, Labels.IMAGES.getNamePlural() );
	}

	/**
	 * Returns the field in view mode.
	 * @param id
	 * @param entry
	 * @return
	 */
	public static String getFieldInViewMode(  URI uri, boolean showNavigation, boolean showNavigationInEditMode ) throws Exception {
		String ret = "";

		ret += getTitleContainer( model.Labels.IMAGES, false, true );		
		ret += getFormContainer( getFormInViewMode( uri, showNavigation, showNavigationInEditMode ), CSSIDCONTENT );

		// The field is printed in <div id=" fieldIdentifier "> and hence all its components can be accessed with this
		ret = getFieldContainer( ret, CSSIDFIELD );
		
		return ret;
	}
	
	/**
	 * Returns the field in view mode.
	 * @param id
	 * @param entry
	 * @return
	 */
	public static String getFieldInEditMode( URI uri, String entry, ArrayList<Exception> exceptions, boolean showNavigation ) throws Exception {
		String ret = "";
		
		ret += getContentInEditMode(uri, entry, exceptions, showNavigation);

		// The field is printed in <div id=" fieldIdentifier "> and hence all its components can be accessed with this
		ret = getFieldContainer( ret, CSSIDFIELD );
		
		return ret;
	}
	
	public static String getContentInEditMode( URI uri, String entry, ArrayList<Exception> exceptions, boolean showNavigation ) throws Exception {
		
		String ret = "";
		
		ret += getTitleContainer( model.Labels.IMAGES, false, true );		
		ret += getFormContainer( getFormInEditMode( uri, entry, exceptions, showNavigation ), CSSIDCONTENT );
		
		return ret;
	}
	
	public static String getFormInViewMode( URI uri, boolean showNavigation, boolean showNavigationInEditMode ) throws Exception {

		String ret = "";

		java.util.ArrayList<String> list = Mapper.selectImages( uri );	
		String content = getFlickrImagesHTML(list);	

		ret = renderViewForm( 
				content, 
				Mapper.selectHasVersionDateTimeString(uri),
				CSSIDCONTENT, 
				showNavigation, 
				showNavigationInEditMode );
		
		return ret;
	}
	
	

	private static String getFlickrImagesHTML( ArrayList<String> entry ) throws Exception {
		String ret = "";
		
		if( entry!=null ) {
			
			for( int i = 0; i<entry.size(); i++ ) {
						
				PhotosService ps = new PhotosService();
				try {
					PhotoResponse res = ps.getInfo( entry.get(i) );					

					//String src = res.getThumbnailUrl().toString();
					String preview = res.getThumbnailUrl().toString();
					String photopage = "http://www.flickr.com/photos/" + res.getOwner().getUserId() + "/" + entry.get(i);
					//String id = res.getPhotoId();
					
					String license = res.getLicense(); // the license-string cannot be queried by quickr-API. Hopefully it will come in short a new release.
					String licensetxt = "";
					// TODO: check for updated releas of quickr, wich supports photos.licenses.getInfo( id ).getName() and getUrl() or similar.
					String licenseURL = "";
					if( license.equals("0")) {
						licensetxt = "All Rights Reserved";
						licenseURL = "";
					} else if( license.equals("1")) {
						licensetxt = "Attribution-NonCommercial- ShareAlike License";
						licenseURL = "http://creativecommons.org/licenses/by-nc-sa/2.0/";
					} else if( license.equals("2")) {
						licensetxt = "Attribution-NonCommercial License";
						licenseURL = "http://creativecommons.org/licenses/by-nc/2.0/";
					} else if( license.equals("3")) {
						licensetxt = "Attribution-NonCommercial- NoDerivs License";
						licenseURL = "http://creativecommons.org/licenses/by-nc-nd/2.0/";
					} else if( license.equals("4")) {
						licensetxt = "Attribution License)";
						licenseURL = "http://creativecommons.org/licenses/by/2.0/";
					} else if( license.equals("5")) {
						licensetxt = "Attribution-ShareAlike License";
						licenseURL = "http://creativecommons.org/licenses/by-sa/2.0/";
					} else if( license.equals("6")) {
						licensetxt = "Attribution-NoDerivs License";
						licenseURL = "http://creativecommons.org/licenses/by-nd/2.0/";
					}
					
					if(!licenseURL.equals("")) {
						license = "<a href=\\'" + licenseURL + "\\' target=\\'_blank\\'>" + licensetxt + "</a>";
					}
					
					String owner = "<a href=\\'http://www.flickr.com/photos/" + res.getOwner().getUserId() + "\\' target=\\'_blank\\'>" + res.getOwner().getUserId() + "</a>";
					
					String onmouseover = StringEscapeUtils.escapeHtml( "myFlickrTip('<div class=\\'flickrpreview\\'><img src=\\'" + res.getSmallUrl().toString() + "\\' alt=\\'" + res.getSmallUrl().toString() + "\\' /><div style=\\'text-align:left;\\'>All rights reserved.<br />License: " + license + "<br />Owner (Flickr ID): " + owner + "</div></div>')" );				
					
					ret += "<a onmouseover=\"" + onmouseover + "\" href=\"" + photopage + "/\" target=\"_blank\"><img class=\"flickrImage\" src=\"" + preview + "\" alt=\"" + preview + "\" /></a>";
					//ret += "insertImage('" + src + "','" + id + "','" + preview + "');";
					// System.out.println( src );
				}
				catch( Exception e ) {
					logger.error( "Image cannot be retrieved from flickr: " + entry.get(i) );
				}	
			}
		}
		
		if( ret.equals("") )
			ret = NOTHINGSELECTED;
		
		return ret;	
	}
	
	

	
	public static String getFormInEditMode( URI uri, String entry, ArrayList<Exception> exceptions, boolean showNavigation ) throws Exception {
		
		String ret = "";

		String actualVersionContent = NOTHINGSELECTED;
		String actualTimestamp = Mapper.selectHasVersionDateTimeString(uri);
		
		if( uri!=null ) {
			
			ArrayList<String> tmp = Mapper.selectImages( uri );			
			if( tmp!=null ) {	
				actualVersionContent = getFlickrImagesHTML( tmp );
			}
		}

		if(entry==null)
			entry="";

		String content = getFlickrImagesEditHTML( entry, Mapper.selectLabel( uri, Vocabulary.ENGLISH) );
		

		ret = renderEditForm( 
				Labels.IMAGES, 
				content,
				exceptions, 
				actualVersionContent, 
				actualTimestamp,
				CSSIDCONTENT, 
				NAMEFORMELEMENT, 
				showNavigation );


		return ret;
	}
	
	private static String getFlickrImagesEditHTML( String entry, String fill ) throws Exception {

		String ret = "";
		
		if( fill==null )
			fill = "";


		
		// #########################################
		
		String selectedContent = 
			"	<div id=\"" + NAMEFORMELEMENT + "_act\" >"; // WITHOUT "\n" !!!

		// the actual values	
		ArrayList<String> strarray = HelperFunctions.extractStrings(entry);
		if( strarray!=null ) {
			for( int i = 0; i<strarray.size(); i++ ){
					
				selectedContent += getFlickrImage( strarray.get(i) );
			}
		}				
				
		selectedContent +=
			"	</div>\n";

		// #########################################
		// #########################################
		
		
		String addContent = 
			"	<div>\n";

		addContent += getDeleteButton(NAMEFORMELEMENT);

		addContent +=
			"		<div class=\"addcontainer\">\n";
		// the selectable items:
		addContent += 	
			"<input type=\"radio\" name=\"imagesRadio\" id=\"flickrTags\" value=\"flickrTags\" checked=\"checked\">Only Tags " +
			"<input type=\"radio\" name=\"imagesRadio\" id=\"flickrFulltext\" value=\"flickrFulltext\">Fulltext " +
			"<input type=\"radio\" name=\"imagesRadio\" id=\"flickrUri\" value=\"flickrUri\"><a href=\"http://www.flickr.com/\" onmouseover=\"myTip('Any page in Flickr which shows a photo.')\" target=\"_blank\">Flickr Photopage</a> (URI)" +
			"<br />\n" +
			" <input style=\"width: 200px;\" type=\"text\" " +
			"onkeypress=\"if((event.keyCode==13)){document.getElementById('flickrButton').click();}\" " +
			"onblur=\"onkeyup();\" onkeyup=\"" +
				"if( this.value.trim()!='' ) " +
					"document.getElementById('flickrButton').disabled=false; " +
				"else " +
					"document.getElementById('flickrButton').disabled=true;" +
			"\" " +
			"autocomplete=\"off\" value=\"" + fill + "\" size=\"60\" id=\"" + NAMEFORMELEMENT + "_input\">";
		
		addContent += 			
			" <input type=\"button\" ";
		if( fill.equals("") )
			addContent += "disabled=\"true\" ";				
		addContent += 	
			"id=\"flickrButton\" value=\"Flickr Search*\" onclick=\"javascript:var selVal=GetSelectedRadioValue(document.getElementsByName('imagesRadio'));" +
			"if(selVal==document.getElementById('flickrFulltext').value){" +
			"	searchFlickrImages('"+NAMEFORMELEMENT+"_sel',document.getElementById('" + NAMEFORMELEMENT + "_input').value," + model.DHTMLConstants.SEARCHFLICKRIMAGESBYTEXT + ");" +
			"}else if(selVal==document.getElementById('flickrTags').value){" +
			"	searchFlickrImages('"+NAMEFORMELEMENT+"_sel',document.getElementById('" + NAMEFORMELEMENT + "_input').value," + model.DHTMLConstants.SEARCHFLICKRIMAGESBYTAGS + ");" +
			"}else if(selVal==document.getElementById('flickrUri').value){" +
			"	extractPhotoId('"+NAMEFORMELEMENT+"_sel',document.getElementById('" + NAMEFORMELEMENT + "_input').value," + model.DHTMLConstants.SEARCHFLICKRIMAGESBYID + ");" +
			"}" +
			"\">\n";
		addContent += 
			"			<div class=\"inputhint\">Input text which describes the searched best (or the URI of a Flickr image).</div>\n";
		addContent += 
			"			<div id=\"" + NAMEFORMELEMENT + "_sel\"></div>\n";
		addContent += 
			"		</div>\n";
		addContent +=
			"	</div>\n";
		
		addContent += 
			"	<div class=\"clearer\">&nbsp;</div>\n";

			// #########################################
			// #########################################

		
		ret = selectedContent + addContent;
		

		
		
		// the actual values (again; this field is filled / decreased with DHTML but has to be "initialized")
		ret +=
			"<input type=\"hidden\" name=\"" + NAMEFORMELEMENT + "\" value=\"" + entry + "\" />\n";



		
		return ret;
	}
	
	public static String getFlickrImage( String flickrPhotoId ) {

		String ret = "";
		
		try {
			
			PhotosService ps = new PhotosService();
			
			PhotoResponse res = ps.getInfo( flickrPhotoId );

			String src = res.getThumbnailUrl().toString();
			String preview = res.getSmallUrl().toString();
			String id = res.getPhotoId();					
			
			ret += getImageHTML( 
					id, 
					src, 
					"myFlickrTip('<div class=\\'flickrpreview\\'><img src=\\'"+preview+"\\'/></div>')",
					"toggleBackground(document.getElementById('" + id + "'));toggleBackground(this);hideDeleteButtonIfNothingSelected('"+NAMEFORMELEMENT + "_act','"+NAMEFORMELEMENT + "_deletebuttonid');return false;" );

		}
		catch( Exception e ) {
			logger.error( "Image cannot be retrieved from flickr: " + flickrPhotoId );
		}
		
		return ret;
	}

	// used for flickr and youtube to get the preview.
	private static String getImageHTML( String id, String imgSrc, String onmouseoverevent, String onclickevent ){

		return "<span id=\"" + id + "\" class=\"selectedElement selectedImage\"><img src=\"" + imgSrc + "\" class=\"spanImageThumb\" onmouseover=\"" + onmouseoverevent + "\" onclick=\"" + onclickevent + "\" /></span>"; // WITHOUT "\n" !!!
	}
	
}
